import Taro from "@tarojs/taro";
import { useUserStore } from "../store";
let needLoadingRequestCount = 0;
// loading配置，请求次数统计
function startLoading() {
  Taro.showLoading({ title: "加载中", mask: true });
}
function endLoading() {
  Taro.hideLoading();
} // 声明一个对象用于存储请求个数
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}
//loading是做了多个请求同时发起的时候防止动画叠加

export default function request(url, config: any = {}, needLoading = false) {
  const BASE_URL = "http://192.168.110.171:5201";

  //默认加载都带动画设置false不加载
  const userStore = useUserStore();
  needLoading && showFullScreenLoading();
  return new Promise((resolve, reject) => {
    Taro.request({
      url: `${BASE_URL}${url}`,
      method: config.type.toUpperCase() || "GET",
      data: config.data || {},
      timeout: 10000,
      header: {
        "Content-type": config.paramsFormdata || "application/json",
        "user-token": userStore.Token || "",
        ...config.header,
      },

      success: (result) => {
        const { statusCode, data } = result;
        if (statusCode === 200) {
          resolve(data);
        } else if (statusCode === 401) {
          Taro.removeStorageSync("TOKEN");
          Taro.removeStorageSync("userInfo");
          setTimeout(() => {
            Taro.redirectTo({
              url: "/pages/login/index",
            });
          }, 500);
        }
      },
      fail: (error) => {
        Taro.showToast({
          title: "网络错误",
          icon: "none",
        });
        return error;
      },
      complete: (res) => {
        // tryHideFullScreenLoading();
      },
    });
  });
}
